package com.woniu.zsd.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageInfo;
import com.woniu.dto.UserDto;
import com.woniu.dto.UserInfoDto;
import com.woniu.form.AddPointForm;
import com.woniu.form.SelUserForm;
import com.woniu.form.UpdatePwdForm;
import com.woniu.form.UpdateUserInfoForm;
import com.woniu.zsd.commons.core.model.Result;
import com.woniu.zsd.user.entity.User;
import com.woniu.zsd.user.entity.UserInfo;
import com.woniu.zsd.user.entity.UserAddress;
import com.woniu.zsd.user.mapper.UserAddressMapper;
import com.woniu.zsd.user.mapper.UserInfoMapper;
import com.woniu.zsd.user.mapper.UserMapper;
import com.woniu.zsd.user.service.IUserInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2025-03-27
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements IUserInfoService {
    @Autowired
    private UserAddressMapper userAddressMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public UserInfoDto selUserInfo(String id) {
        UserInfoDto dto = new UserInfoDto();
        UserInfo userInfo = baseMapper.selectById(id);
        //查询所有用户所关联的的地址
        QueryWrapper<UserAddress> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userInfo.getUserId());
        List<UserAddress> userAddresses = userAddressMapper.selectList(queryWrapper);
        queryWrapper.eq("default_mark", "1");
        UserAddress userAddress = userAddressMapper.selectOne(queryWrapper);
        //查询用户的手机号
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("id", userInfo.getUserId());
        User user = userMapper.selectOne(userQueryWrapper);
        //将查询出的地址放到List中
        List<String> addresses = userAddresses.stream().map(UserAddress::getAddress).collect(Collectors.toList());
        QueryWrapper<UserAddress> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("user_id", userInfo.getUserId()).eq("default_mark", "1");
        UserAddress userAddress1 = userAddressMapper.selectOne(queryWrapper1);
        //将数据保存到dto中
        dto.setAddress(addresses);
        dto.setPhone(user.getPhone());
        dto.setRegisterTime(user.getRegisterTime());
        if (userAddress1 != null) {
            dto.setDefaultAddress(userAddress1.getAddress());
        } else {
            dto.setDefaultAddress("默认地址未设置");
        }
        BeanUtil.copyProperties(userInfo, dto);
        System.out.println(dto);
        return dto;
    }

    @Override
    public UserInfo updateUserInfo(UpdateUserInfoForm uuif, String id) throws IOException {
        UserInfo userInfo = baseMapper.selectById(id);
        // 如果 nickName 不为空，则更新昵称
        if (uuif.getNickName()!= null && !uuif.getNickName().trim().isEmpty()) {
            userInfo.setNickName(uuif.getNickName());
        }
        // 如果 headImage 不为空，则更新头像
        if (uuif.getHeadImage()!= null && !uuif.getHeadImage().trim().isEmpty()) {
            userInfo.setHeadImage(uuif.getHeadImage());
        }
        baseMapper.updateById(userInfo);
        return userInfo;
    }

    @Override
    public Result updatePassword(UpdatePwdForm upf, String id) {
        // 1. 查询用户信息
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("username", upf.getUsername());
        UserInfo userInfo = userInfoMapper.selectOne(wrapper);

        // 2. 判断用户是否存在
        if (userInfo == null) {
            throw new RuntimeException("用户不存在");
        }

        // 3. 验证旧密码是否正确
        if (!userInfo.getPassword().equals(upf.getOldPassword())) {
            throw new RuntimeException("旧密码错误");
        }

        // 4. 更新密码
        userInfo.setPassword(upf.getNewPassword());
        int updateResult = userInfoMapper.updateById(userInfo);

        // 5. 判断更新是否成功
        if (updateResult > 0) {
            return Result.getResult(UserInfo.class).setData(userInfo).setMsg("密码修改成功");
        } else {
            throw new RuntimeException("密码修改失败");
        }
    }


    @Override
    public void addPointById(AddPointForm apf) {
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", apf.getId());
        Integer point = ((apf.getTotalAmount().intValue())/10);
        if (apf.getType() == 1){
            UserInfo userInfo = userInfoMapper.selectOne(wrapper);
            userInfo.setPoint(userInfo.getPoint() + point);
            userInfoMapper.updateById(userInfo);
        }else if(apf.getType() == 0){
            UserInfo userInfo = userInfoMapper.selectOne(wrapper);
            userInfo.setPoint(userInfo.getPoint() - 100);
            userInfoMapper.updateById(userInfo);
            if (userInfo.getPoint() < 0){
                userInfo.setPoint(0);
                userInfoMapper.updateById(userInfo);
            }
        }
    }

    @Override
    public PageInfo<UserDto> selUser(SelUserForm suf) {
        // 创建 MyBatis-Plus 的分页对象
        Page<UserDto> page = new Page<>(suf.getPageNum() != null ? suf.getPageNum() : 1, suf.getPageSize() != null ? suf.getPageSize() : 10);
        
        // 调用 Mapper 中的方法进行分页查询
        List<UserDto> userDtos = userInfoMapper.findUser(suf);
        
        // 将查询结果设置到分页对象中
        page.setRecords(userDtos);
        page.setTotal(userDtos.size()); // 这里假设总数为查询结果的数量，实际应根据数据库查询的总数设置
        
        // 将 MyBatis-Plus 的 Page 对象转换为 PageInfo 对象
        PageInfo<UserDto> pageInfo = new PageInfo<>(page.getRecords());
        pageInfo.setPageNum((int) page.getCurrent());
        pageInfo.setPageSize((int) page.getSize());
        pageInfo.setTotal(page.getTotal());
        
        return pageInfo;
    }

    @Override
    public List<UserDto> selUserInfoByIds(Set<Integer> ids) {
        if (ids != null && !ids.isEmpty()) {
            List<UserDto> userDtos = userInfoMapper.findUserInfoByIds(ids);
            return userDtos;
        }
        return Collections.emptyList();
    }
}